package main

import (
	"context"
	"fmt"
	"os"
	"time"
	"wanfang-translation/internal/service"
	"wanfang-translation/internal/service/check"
	"wanfang-translation/internal/service/exception"

	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

// 直接对原文进行查重服务

// Config 配置结构体
type Config struct {
	RabbitMQ struct {
		Host     string `mapstructure:"host"`
		Port     int    `mapstructure:"port"`
		User     string `mapstructure:"user"`
		Password string `mapstructure:"password"`
	} `mapstructure:"rabbit_mq"`
	Cn2En service.TranslationConfig `mapstructure:"cn2en"`
	En2Cn service.TranslationConfig `mapstructure:"en2cn"`
}

// rabbit_mq队列配置
type RabbitMQConfig struct {
	MqURL            string
	OriginCheckQueue string
}

func main() {
	// 设置工作路径
	setProjectRoot()

	// 加载配置
	config, err := loadConfig()
	if err != nil {
		exception.LogError(exception.NewSystemError("加载配置失败" + err.Error()))
		return
	}

	// 构建 MQ URL
	mqURL := fmt.Sprintf("amqp://%s:%s@%s:%d/",
		config.RabbitMQ.User,
		config.RabbitMQ.Password,
		config.RabbitMQ.Host,
		config.RabbitMQ.Port,
	)

	// 构建rabbit_mq队列配置
	rabbitMQConfig := RabbitMQConfig{
		MqURL:            mqURL,
		OriginCheckQueue: "origin_check_queue",
	}

	// TODO: 运行该原文查重服务时注意需要修改存储的配置文件路径
	statistics := service.NewStatistics()

	// 开启查重服务
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
	defer cancel()

	// 连接到 gRPC 服务器
	conn, err := grpc.DialContext(ctx, "grpccheckservice.imagedetect:80", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock())
	if err != nil {
		exception.LogError(exception.NewSystemError("连接服务器失败" + err.Error()))
		return
	}
	defer conn.Close()

	client := check.NewCheckClient(conn)

	checkServiceConfig := service.NewCheckService()

	service.StartCheckService(rabbitMQConfig.MqURL, rabbitMQConfig.OriginCheckQueue, "", checkServiceConfig, client, statistics)

	select {} // 阻塞主线程
}

func loadConfig() (*Config, error) {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("config")

	if err := viper.ReadInConfig(); err != nil {
		return nil, err
	}

	var config Config
	if err := viper.Unmarshal(&config); err != nil {
		return nil, err
	}

	return &config, nil
}

// 设置工作路径，并完成路径变更
func setProjectRoot() {
	projectRoot := "../.." // 替换为你的项目根目录路径
	if err := os.Chdir(projectRoot); err != nil {
		exception.LogError(exception.NewSystemError("设置工作目录失败" + err.Error()))
	}
}
